package com.cloud.xtools.common.domain.resource;

import cn.hutool.core.bean.BeanUtil;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @author Daixinguo
 */
public class BaseResource<T> {

    public static <T> T collection(Object entity){
        try {
            // 获取调用该方法的类的类型
            StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
            for (StackTraceElement stackTraceElement : stackTrace){
                System.out.println(stackTraceElement.getClassName());
            }
            Class<?> callerClass = Class.forName(stackTrace[2].getClassName());

            // 获取泛型类型
            Type genericSuperclass = callerClass.getGenericSuperclass();
            System.out.println(genericSuperclass);
            if (genericSuperclass instanceof ParameterizedType parameterizedType) {
                Class<T> resourceClass = (Class<T>) parameterizedType.getActualTypeArguments()[0];
                System.out.println(resourceClass);
                return BeanUtil.copyProperties(entity, resourceClass);
            } else {
                throw new RuntimeException("Caller class is not a generic type");
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to determine resource class", e);
        }
    }
}
